<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑工序' : '新增工序'"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工序编号" prop="operationCode">
            <el-input
              v-model="formData.operationCode"
              placeholder="请输入工序编号"
            >
              <template #append>
                <el-button 
                  @click="generateCode('GX_')" 
                  :loading="codeGenerating"
                  type="primary"
                >
                  生成编码
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工序名称" prop="operationName">
            <el-input
              v-model="formData.operationName"
              placeholder="请输入工序名称"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="前置工序" prop="preOperationId">
            <el-select
              v-model="formData.preOperationId"
              placeholder="请选择前置工序"
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              style="width: 100%"
            >
              <el-option
                v-for="op in otherOperations"
                :key="op.id"
                :label="op.operationName"
                :value="op.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="后置工序" prop="sufOperationId">
            <el-select
              v-model="formData.sufOperationId"
              placeholder="请选择后置工序"
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              style="width: 100%"
            >
              <el-option
                v-for="op in otherOperations"
                :key="op.id"
                :label="op.operationName"
                :value="op.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="标准时长" prop="operationTotalStdTime">
            <el-input-number
              v-model="formData.operationTotalStdTime"
              :min="0"
              :precision="0"
              :step="1"
              placeholder="标准时长（分钟）"
              style="width: 100%"
            />
            <span class="unit-tip">分钟</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="准备时长" prop="operationPreparedTime">
            <el-input-number
              v-model="formData.operationPreparedTime"
              :min="0"
              :precision="0"
              :step="1"
              placeholder="准备时长（分钟）"
              style="width: 100%"
            />
            <span class="unit-tip">分钟</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="设备类型" prop="operationEquipType">
            <el-select
              v-model="formData.operationEquipType"
              placeholder="请选择设备类型"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="type in equipmentTypeOptions"
                :key="type"
                :label="type"
                :value="type"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="人员技能" prop="operationPersonSkill">
        <el-input
          v-model="formData.operationPersonSkill"
          placeholder="请输入所需人员技能"
        />
      </el-form-item>

      <el-form-item label="工序描述" prop="operationDescription">
        <el-input
          v-model="formData.operationDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入工序描述"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        {{ isEdit ? "更新" : "保存" }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import { operationApi } from "@/api/operation";
import basicEquipApi from "@/api/basicEquip";
import { codeGeneratorApi } from "@/api/codeGenerator";

export default {
  name: "OperationFormDialog",
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    operationData: {
      type: Object,
      default: null,
    },
    craftInfo: {
      type: Object,
      required: true,
    },
    allOperations: {
      type: Array,
      default: () => [],
    },
  },
  emits: ["update:modelValue", "saved"],
  setup(props, { emit }) {
    const formRef = ref();
    const saving = ref(false);
    const equipmentTypeOptions = ref([]);
    const codeGenerating = ref(false);

    // 对话框显示状态
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit("update:modelValue", val),
    });

    // 是否为编辑模式
    const isEdit = computed(() => {
      return props.operationData && props.operationData.id;
    });

    // 获取其他工序（排除当前工序）
    const otherOperations = computed(() => {
      if (!props.allOperations) return [];
      return props.allOperations.filter(
        (op) => op.id !== formData.id,
      );
    });

    // 表单数据
    const formData = reactive({
      id: "",
      operationCode: "",
      operationName: "",
      craftId: "",
      craftCode: "",
      operationTotalStdTime: null,
      operationDescription: "",
      preOperationId: [],
      sufOperationId: [],
      operationPreparedTime: null,
      operationEquipType: "",
      operationPersonSkill: "",
    });

    // 表单验证规则
    const formRules = {
      operationCode: [
        { required: true, message: "请输入工序编号", trigger: "blur" },
      ],
      operationName: [
        { required: true, message: "请输入工序名称", trigger: "blur" },
      ],
      operationTotalStdTime: [
        { required: true, message: "请输入标准时长", trigger: "blur" },
      ],
    };

    // 将字符串转换为数组（处理逗号分隔的ID字符串）
    const stringToArray = (str) => {
      if (!str) return [];
      if (Array.isArray(str)) return str;
      return str
        .toString()
        .split(",")
        .map((id) => id.trim())
        .filter((id) => id);
    };

    // 将数组转换为字符串（逗号分隔）
    const arrayToString = (arr) => {
      if (!arr || !Array.isArray(arr)) return "";
      return arr.filter((id) => id).join(",");
    };

    // 监听对话框显示状态，填充表单
    watch(
      () => props.modelValue,
      (newVal) => {
        if (newVal) {
          // 加载设备类型
          loadEquipmentTypes();
          if (props.operationData) {
            // 编辑模式：需要将字符串格式的ID转换为数组
            const data = { ...props.operationData };
            data.preOperationId = stringToArray(data.preOperationId);
            data.sufOperationId = stringToArray(data.sufOperationId);
            Object.assign(formData, data);
          } else {
            resetForm();
            // 新增时设置工艺信息
            formData.craftId = props.craftInfo.id;
            formData.craftCode = props.craftInfo.craftCode;
          }
        }
      },
    );

    // 重置表单
    const resetForm = () => {
      Object.assign(formData, {
        id: "",
        operationCode: "",
        operationName: "",
        craftId: "",
        craftCode: "",
        operationTotalStdTime: null,
        operationDescription: "",
        preOperationId: [],
        sufOperationId: [],
        operationPreparedTime: null,
        operationEquipType: "",
        operationPersonSkill: "",
      });
      formRef.value?.clearValidate();
    };

    // 生成编码
    const generateCode = async (prefix) => {
      try {
        codeGenerating.value = true;
        const response = await codeGeneratorApi.gen({ prefix });
        if (response && response.data) {
          formData.operationCode = response.data;
          ElMessage.success('编码生成成功');
        } else {
          ElMessage.error('编码生成失败');
        }
      } catch (error) {
        console.error('生成编码失败:', error);
        ElMessage.error('生成编码失败: ' + (error.message || '未知错误'));
      } finally {
        codeGenerating.value = false;
      }
    };

    // 关闭对话框
    const handleClose = () => {
      visible.value = false;
      resetForm();
    };

    // 保存工序
    const handleSave = async () => {
      try {
        // 表单验证
        await formRef.value.validate();

        saving.value = true;

        // 确保工艺信息存在，并将数组转换为逗号分隔的字符串
        const saveData = {
          ...formData,
          craftId: props.craftInfo.id,
          craftCode: props.craftInfo.craftCode,
          // 将数组转换为逗号分隔的字符串
          preOperationId: arrayToString(formData.preOperationId),
          sufOperationId: arrayToString(formData.sufOperationId),
        };

        console.log("保存工序数据:", saveData);

        let savedData = null;

        if (formData.id) {
          // 更新工序
          await operationApi.updateOperation(saveData);
          ElMessage.success("工序更新成功");
          savedData = { ...saveData };
        } else {
          // 创建工序
          const response = await operationApi.createOperation(saveData);
          ElMessage.success("工序创建成功");
          savedData = response.data || { ...saveData };
        }

        // 触发保存事件，传递保存后的数据
        emit("saved", savedData);
        handleClose();
      } catch (error) {
        if (error !== false) {
          // 忽略表单验证失败
          console.error("保存工序失败:", error);
          ElMessage.error("保存工序失败: " + (error.message || "未知错误"));
        }
      } finally {
        saving.value = false;
      }
    };

    // 加载设备类型选项（去重）
    const loadEquipmentTypes = async () => {
      try {
        const resp = await basicEquipApi.getEquipsByCurrentTenant();
        const list = (resp && resp.data) ? resp.data : [];
        const types = list
          .map((item) => item?.type || item?.equipType || item?.equipmentType || item?.category)
          .filter((t) => t && typeof t === "string");
        equipmentTypeOptions.value = Array.from(new Set(types));
      } catch (e) {
        // 兜底：尝试获取全部
        try {
          const respAll = await basicEquipApi.getAllEquipss();
          const listAll = (respAll && respAll.data) ? respAll.data : [];
          const typesAll = listAll
            .map((item) => item?.type || item?.equipType || item?.equipmentType || item?.category)
            .filter((t) => t && typeof t === "string");
          equipmentTypeOptions.value = Array.from(new Set(typesAll));
        } catch (err) {
          console.error("加载设备类型失败", err);
          equipmentTypeOptions.value = [];
        }
      }
    };

    return {
      formRef,
      visible,
      isEdit,
      formData,
      formRules,
      saving,
      otherOperations,
      equipmentTypeOptions,
      codeGenerating,
      generateCode,
      handleClose,
      handleSave,
    };
  },
};
</script>

<style scoped>
.unit-tip {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>
